const Router = require('koa-router');
const router = new Router();
const {db,QueryTypes} = require("../../models/db");
const tool = require("../../tools/tool");

router.post('/goods/list', async ctx => {
    let tenantId = ctx.user.tenantId
    let body = ctx.request.body
    let formData = body.formData
    let excel = body.excel
    let goodCatCode = await tool.getGoodCode(ctx)
    let name = formData.name
    let barCode = formData.barCode
    let brandId = formData.brandId
    let hjId = formData.hjId
    let sql = `select * from v_goods where tenantId=${tenantId} `
    if(goodCatCode) {
        sql += ` and goodCatCode like '${goodCatCode}%'`
    }
    if(name) {
        sql += ` and name like '%${name}%' `
    }
    if(barCode) {
        sql += ` and (barCode like '%${barCode}%' or barCode1 like '%${barCode}%' ) `
    }
    if(hjId) {
        sql += ` and hjId=${hjId} `
    }
    if(brandId) {
        sql += ` and brandId=${brandId} `
    }
    sql += ' order by goodCatCode,name '
    let list = await db.query(sql, {type: QueryTypes.SELECT})
    if(excel) {
        return tool.doExcelOut(ctx,list,)
    }

    return ctx.suc('', {
        list
    })

})
router.post('/goods/getUnitById', async ctx => {
    let tenantId = ctx.user.tenantId
    let invId = ctx.request.body.id
    let good = await db.models['goods'].findOne({
        where: {
            id: invId,
            tenantId
        },
        attributes: ['id', 'name', 'unit1', 'unit2', 'spec','unit1Id','unit2Id']
    })
    return ctx.suc('', good)
})



module.exports = router;
